# import cv2
#
# img = cv2.imread('pic/one.jpg')
# face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
# smile_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_smile.xml')
# upperbody_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_upperbody.xml')
#
#
# faces=face_cascade.detectMultiScale(img,1.2,5)
#
# for (x, y, w, h) in faces:
#         # 画出人脸框，蓝色，画笔宽度微
#         img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
#         # 框选出人脸区域，在人脸区域而不是全图中进行人眼检测，节省计算资源
#         face_area = img[y:y + h, x:x + w]
#         # eyes = eye_cascade.detectMultiScale(face_area)
#         # 用人眼级联分类器引擎在人脸区域进行人眼识别，返回的eyes为眼睛坐标列表
#         # for (ex, ey, ew, eh) in eyes:
#         #     # 画出人眼框，绿色，画笔宽度为1
#         #     cv2.rectangle(face_area, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 1)
#
# smile= smile_cascade.detectMultiScale(img)
# for (ex, ey, ew, eh) in smile:
#     # 画出人眼框，绿色，画笔宽度为1
#      cv2.rectangle(img, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 1)
#
#
#
# # 实时展示效果画面
# cv2.imshow('frame2', img)
#  # 每5毫秒监听一次键盘动作
# cv2.waitKey(0)
# # 最后，关闭所有窗口
# cv2.destroyAllWindows()

import cv2
import numpy as np
import matplotlib.pyplot as plt

# 图像二值化处理
def imgThreshold(img):
    rosource, binary = cv2.threshold(img, 121, 255, cv2.THRESH_BINARY)
    return binary

# 1.先水平分割，再垂直分割
# 对图片进行垂直分割
def verticalCut(img):
    (x, y) = img.shape  # 返回的分别是矩阵的行数和列数，x是行数，y是列数
    pointCount = np.zeros(y, dtype=np.float32)  # 每列黑色的个数
    x_axes = np.arange(0, y)
    # i是列数，j是行数
    tempimg = img.copy()
    for i in range(0, y):
        for j in range(0, x):
            # if j<15:
            if (tempimg[j, i] == 0):
                pointCount[i] = pointCount[i] + 1
    plt.plot(x_axes, pointCount)
    start = []
    end = []
    # 对照片进行分割
    # print(pointCount)
    for index in range(1, y - 1):
        # 上个为0当前不为0，即为开始
        if ((pointCount[index - 1] == 0) & (pointCount[index] != 0)):
            start.append(index)
        # 上个不为0当前为0，即为结束
        elif ((pointCount[index] != 0) & (pointCount[index + 1] == 0)):
            end.append(index)
    imgArr = []
    print(len(end),len(start))
    for i in range(len(end)):
        tempimg = img[:, start[i]:end[i]]
        imgArr.append(tempimg)
    return imgArr

# 对图片进行水平分割,返回照片数组
def horizontalCut(img):
    (x, y) = img.shape  # 返回的分别是矩阵的行数和列数，x是行数，y是列数
    pointCount = np.zeros(y, dtype=np.uint8)  # 每行黑色的个数
    x_axes = np.arange(0, y)
    for i in range(0, x):
        for j in range(0, y):
            if (img[i, j] == 0):
                pointCount[i] = pointCount[i] + 1
    plt.plot(x_axes, pointCount)
    start = []
    end = []
    # 对照片进行分割
    # print(pointCount)
    for index in range(1, y):
        # 上个为0当前不为0，即为开始
        if ((pointCount[index] != 0) & (pointCount[index - 1] == 0)):
            start.append(index)
        # 上个不为0当前为0，即为结束
        elif ((pointCount[index] == 0) & (pointCount[index - 1] != 0)):
            end.append(index)
    newimg = {}
    for i in range(len(start)):
        newimg[i] = img[start[i]:end[i], :]
    cv2.waitKey()
    # plt.show()
    return newimg

# 输入的分别是原图,模板和标签
def matchTemplate(src, matchSrc, label):
    src = cv2.resize(src,(21,28))
    # cv2.imshow('binaryc', binaryc)

    # result = cv2.matchTemplate(binaryc, matchSrc, cv2.TM_CCOEFF_NORMED)
    # min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    res = cv2.matchTemplate(src, matchSrc, cv2.TM_CCOEFF_NORMED)
    threshold = 0.4
    # h, w = matchSrc.shape[:2]
    loc = np.where(res >= threshold)  # 匹配程度大于%80的坐标y,x
    loc = np.array(loc)
    print(loc.shape[1])
    if loc.shape[1] != 0:
        cv2.imshow('001', src)
        print("Find it!")
    # for pt in zip(*loc[::-1]):  # *号表示可选参数
    #     right_bottom = (pt[0] + w, pt[1] + h)
    #     cv2.rectangle(src, pt, right_bottom, (0, 0, 255), 2)
    #     cv2.waitKey(0)
    # tw, th = matchSrc.shape[:2]
    # tl = (max_loc[0] + th + 2, max_loc[1] + tw + 2)
    # cv2.rectangle(src, max_loc, tl, [0, 0, 0])
    # cv2.putText(src, label, max_loc, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=0.6,
    #             color=(240, 230, 0))
    # cv2.imshow('001', src)

# 先读取图片
img = cv2.imread("pic/word.png")
match = cv2.imread('pic/temple/01.bmp')
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
match = cv2.cvtColor(match,cv2.COLOR_RGB2GRAY)
img = imgThreshold(img)

match = imgThreshold(match)
result = horizontalCut(img)
for i in range(len(result)):
    result1 = verticalCut(result[i])
    # 再读取分割好的图片
    for j in range(len(result1)):
        matchTemplate(result1[j], match, '1')

cv2.waitKey(0)
cv2.destroyAllWindows()


